package com.tronsis.distribution.fragment.material;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.tronsis.distribution.Constants;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.ResourceBean;
import com.tronsis.distribution.biz.factory.ResourceBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.DownloadUtil;
import com.tronsis.library.util.EasyPermissions;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.CircleImageView;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

/**
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class CategoryFragment extends BaseFragment {

    @BindView(R.id.srl_material)
    SwipeRefreshLayout mSrl;
    @BindView(R.id.rv_material)
    RecyclerView mRvMaterial;

    private CommonAdapter<ResourceBean> mAdapter;
    private List<ResourceBean> mMaterialList = new ArrayList<>();

    private LoadMoreWrapper mLoadMoreWrapper;
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private String mTypeId;
    private String mSearch;

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_category, null);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        mTypeId = bundle.getString("typeId");
        LogUtil.e("CategoryFragment", "typeId = " + mTypeId);

        initRv();
        httpGetResource(1, mSize, true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        switch (message.getTag()) {
            case EventTag.MATERIAL_SEARCH:
                mSearch = (String) message.getParams();
                httpGetResource(1, mSize, true);
                break;
            default:
                break;
        }
    }

    private void initRv() {
        ImagePicker.getInstance().setImageLoader(new GlideImageLoader());
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpGetResource(1, mSize, true);
            }
        });

        mAdapter = new CommonAdapter<ResourceBean>(getContext(), mMaterialList, R.layout.item_material) {
            @Override
            protected void convert(ViewHolder holder, final ResourceBean resourceBean, int position) {
                CircleImageView iv = holder.getView(R.id.iv_avatar);
                if (!TextUtils.isEmpty(resourceBean.getAdminId())) {
                    iv.setImageResource(R.drawable.web_image);
                } else {
                    ImageLoader.displayAvatar(mContext, Url.FILE_DOWNLOAD + resourceBean.getCreatorImage(), iv);
                }

                holder.setText(R.id.tv_creator, resourceBean.getCreatorName());
                holder.setText(R.id.tv_date, DateUtil.getDateTimeString(resourceBean.getCreatedOn()));
                holder.setText(R.id.tv_content, resourceBean.getContent());
                holder.setText(R.id.tv_type, getString(R.string.format_type, resourceBean.getTypeName()));

                holder.setOnClickListener(R.id.iv_copy, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 创建普通字符型ClipData
                        ClipData mClipData = ClipData.newPlainText("", resourceBean.getContent());
                        // 将ClipData内容放到系统剪贴板里。
                        ClipboardManager myClipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                        myClipboard.setPrimaryClip(mClipData);
                        ToastUtil.showMessage(mContext, "复制成功");
                    }
                });

                final String videoFid = resourceBean.getVideoFid();
                final String imageFid = resourceBean.getImageFid();

                holder.setOnClickListener(R.id.iv_download, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!EasyPermissions.hasPermissions(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            EasyPermissions.requestPermissions(mContext, getString(R.string.perm_tip), 0x111, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                            return;
                        }
                        List<DownloadFile> list = new ArrayList<>();
                        if (!TextUtils.isEmpty(imageFid)) {
                            String[] strings = imageFid.split(",");
                            for (String string : strings) {
                                list.add(new DownloadFile(false, string));
                            }
                        }
                        if (!TextUtils.isEmpty(videoFid)) {
                            list.add(new DownloadFile(true, videoFid));
                        }

                        if (!list.isEmpty()) {
                            int[] index = {0};
                            download(list, index);
                        }
                    }
                });

                RecyclerView rv = holder.getView(R.id.rv_image);

                ArrayList<ImageItem> allList = new ArrayList<>();
                if (!TextUtils.isEmpty(videoFid)) {
                    ImageItem imageItem = new ImageItem();
                    imageItem.url = Url.FILE_DOWNLOAD + resourceBean.getVideoFid();
                    imageItem.isVideo = true;
                    allList.add(imageItem);
                }
                ArrayList<ImageItem> splitImage = CommonUtil.getSplitImage(imageFid);
                allList.addAll(splitImage);
                setImageRv(rv, allList, videoFid);
            }
            //add by Allen
            private void setImageRv(RecyclerView mRvUserUpload, final ArrayList<ImageItem> mImageList, String videoFid) {
                CommonAdapter mCustomImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_image_material) {
                    @Override
                    protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                        ImageView ivItem = holder.getView(R.id.iv_item);
                        ImageView ivVideo = holder.getView(R.id.iv_video);

                        if (imageItem.isVideo) {
                            ivItem.setVisibility(View.GONE);
                            ivVideo.setVisibility(View.VISIBLE);
                            ivVideo.setImageResource(R.drawable.icon_video_play);
                            ivVideo.setScaleType(ImageView.ScaleType.CENTER);
                        } else {
                            ivItem.setVisibility(View.VISIBLE);
                            ivVideo.setVisibility(View.GONE);
                            ivItem.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            ivItem.setImageResource(R.color.transparent);
                            ivItem.setBackgroundResource(R.color.transparent);
                            ImageLoader.display(mContext, imageItem.url, ivItem);
                        }

                        ivItem.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intentPreview = new Intent(getContext(), ImageAndVideoPreviewSeeActivity.class);
                                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                                intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                            }
                        });
                        ivVideo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intentPreview = new Intent(getContext(), ImageAndVideoPreviewSeeActivity.class);
                                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                                intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                            }
                        });
                    }
                };
                if (!TextUtils.isEmpty(videoFid)) {
                    mRvUserUpload.setLayoutManager(new LinearLayoutManager(mContext));
                } else {
                    mRvUserUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
                        @Override
                        public boolean canScrollVertically() {
                            return false;
                        }
                    });
                }

                mRvUserUpload.setAdapter(mCustomImageAdapter);
            }
        };


        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mMaterialList.size() % 15 == 0 && mMaterialList.size() > 0 && mMaterialList.size() < mTotal) {
                    mPage = (mMaterialList.size() / 15) + 1;
                    httpGetResource(mPage, mSize, false);
                }
            }
        });
        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRvMaterial.addItemDecoration(decoration);
        mRvMaterial.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvMaterial.setAdapter(mLoadMoreWrapper);
    }

    private class DownloadFile {
        public DownloadFile(boolean isViedo, String url) {
            this.isViedo = isViedo;
            this.url = url;
        }

        private boolean isViedo;
        private String url;

        public boolean isViedo() {
            return isViedo;
        }

        public void setViedo(boolean viedo) {
            isViedo = viedo;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

    private void download(final List<DownloadFile> list, final int[] index) {
        showLoadingDialog();
        DownloadFile downloadFile = list.get(index[0]);
        final String fileName = downloadFile.isViedo ? downloadFile.getUrl() + ".mp4" : downloadFile.getUrl() + ".jpg";
        DownloadUtil.get().download(Url.FILE_DOWNLOAD + downloadFile.getUrl(), Constants.SYSTEM_IMAGE_PATH, fileName, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                refresh();

                index[0] += 1;
                if (index[0] < list.size()) {
                    download(list, index);
                } else {
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoadingDialog();
                            ToastUtil.showMessage(mContext, "下载完成！");
                            list.clear();
                            index[0] = 0;
                        }
                    });

                }

            }

            private void refresh() {
                String type;
                if (fileName.endsWith("mp4")) {
                    type = "video/mp4";
                } else {
                    type = "image/jpeg";
                }
                MediaScannerConnection.scanFile(mContext, new String[]{Constants.SYSTEM_IMAGE_PATH + File.separator + fileName}, new String[]{type},
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Log.d("scanFile", "onScanCompleted : " + path);
                            }
                        });
            }

            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadFailed() {
                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtil.showMessage(mContext, "下载失败");
                    }
                });
            }
        });
    }


    private void httpGetResource(int page, int size, final boolean isRefresh) {
        try {
            LogUtil.e("CategoryFragment-http", "typeId = " + mTypeId);

            ResourceBizFactory.createBiz().getResource(getActivity(), false, page, mSearch, size, mTypeId, new UICallBack() {
                @Override
                public void onStart() {
                    if (isRefresh) {
                        mSrl.setRefreshing(true);
                    }
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<ResourceBean> list = listBean.getList();
                    if (isRefresh) {
                        mMaterialList.clear();
                        mMaterialList.addAll(list);
                    } else {
                        mMaterialList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);

                }
            });
        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }
}
